package com.lzx.applib.utils;

import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.lzx.applib.R;

import static android.R.attr.id;
import static android.content.Context.DOWNLOAD_SERVICE;

/**
 * Created by Lzx on 16/12/22 0022.
 */
public class DownloadManagerUtil {
    public static final String TAG = "DownloadManagerUtil";

    public static long addDownload(Context context, String url, String title, String description, int netType) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setTitle(title);
        request.setDescription(description);
        request.setAllowedNetworkTypes(netType);
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
        long downloadId = downloadManager.enqueue(request);
        return downloadId;
    }

    public static final String getDownloadFile(Context context, long id) {
        String file = null;
        DownloadManager manager = (DownloadManager)context.getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(id);
        Cursor c = manager.query(query);
        if(c.moveToFirst()) {
            file = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
        }
        c.close();
        return file;
    }

    public static final String getDownloadUrl(Context context, long id) {
        String url = null;
        DownloadManager manager = (DownloadManager)context.getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(id);
        Cursor c = manager.query(query);
        if(c.moveToFirst()) {
            url = c.getString(c.getColumnIndex(DownloadManager.COLUMN_URI));
        }
        c.close();
        return url;
    }

    public static final int getDownloadStatus(Context context, long id) {
        int status = DownloadManager.STATUS_FAILED;
        DownloadManager manager = (DownloadManager)context.getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(id);
        Cursor c = manager.query(query);
        if(c.moveToFirst()) {
            status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
        }
        c.close();
        return status;
    }
}
